<template>
  <div class="history">
    <div class="delAll">
      <p>历史记录</p>
      <i class="toutiao toutiao-lajitong" @click="delAll()"></i>
    </div>
    <van-grid :column-num="2" direction="horizontal">
      <van-grid-item v-for="(value, index) in historyData" :key="index" @click="$emit('searchHistoryData',value)">
        <p slot="text">{{ value }}</p>
        <van-icon slot="icon" name="cross" @click="delSingle()" />
      </van-grid-item>
    </van-grid>
  </div>
</template>

<script>
import { delSearchHistory, getSearchHistory } from '@/api/homepage/nav.js'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      historyData: []
    }
  },
  created () {
    this.getHistoryData()
  },
  mounted () {},
  methods: {
    async getHistoryData () {
      // 判断是否登录
      if (this.$store.state.userToken !== null) {
        // 登陆了存储到数据库
        const {
          data: {
            data: { keywords: res }
          }
        } = await getSearchHistory()
        this.historyData = res
        console.log(res)
      } else {
        // 没登录去本地取数据
        this.historyData = getItem('searchHistory')
      }
    },
    // 删除所有
    delAll () {
      // 判断是否登录
      if (this.$store.state.userToken !== null) {
        // 登陆了删除数据库里的信息
        try {
          const { message } = delSearchHistory()
          console.log(message)
          this.historyData = []
          this.$toast.success('删除成功')
        } catch (error) {
          this.$toast.success('删除失败')
        }
      } else {
        // 没登录去本地删除所有
        setItem('searchHistory', [])
        this.historyData = []
        this.$toast.success('删除成功')
      }
    },
    // 删除单个
    delSingle (index) {
      console.log(222)
      // 判断是否登录
      if (this.$store.state.userToken !== null) return
      // 没登录去本地删除数据
      const newData = this.historyData
      newData.splice(index, 1)
      this.historyData = newData
      setItem('searchHistory', newData)
    }
  }
}
</script>

<style lang="less" scoped>
.delAll {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28px;
  color: #666;
  margin-bottom: 15px;
  padding: 0 15px;
  i {
    font-size: 32px;
  }
}
/deep/.van-grid-item__content {
  padding: 20px;
}
/deep/.van-grid-item__content--horizontal {
  display: flex;
  -webkit-flex-direction: none;
  flex-direction: row-reverse;
  justify-content: flex-end;
  justify-content: space-between;
  p {
    font-size: 28px;
  }
  .van-icon-cross {
    font-size: 32px;
  }
}
</style>
